package cn.loioi.web.components.spring;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractCachingViewResolver;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;

/**
 * <br>
 * (c) Copyright 2016 by <br>
 * @description :FastJson 自定义视图解析器 <br>
 * @file_name :FastJsonViewResolver.java <br>
 * @system_name :multi_project_core <br>
 * @author :yyzh <br>
 * @创建时间 :2016年6月3日 下午10:47:42
 */
public class FastJsonViewResolver extends AbstractCachingViewResolver implements Ordered, InitializingBean {
	private int order = 1;
	private String suffix;
	private View view;

	public String getSuffix() {
		return suffix;
	}

	/**
	 * 设置后缀名
	 * @param suffix
	 */
	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public View getView() {
		return view;
	}

	/**
	 * 设置视图
	 * @param view
	 */
	public void setView(View view) {
		this.view = view;
	}

	@Override
	public int getOrder() {
		return order;
	}

	/**
	 * 设置视图等级
	 * @param order
	 */
	public void setOrder(int order) {
		this.order = order;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (view == null) view = new FastJsonJsonView();
		if (StringUtils.isEmpty(suffix)) suffix = ".json";
	}

	@Override
	protected View loadView(String viewName, Locale locale) throws Exception {
		// 获取Request
		RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
		Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
		HttpServletRequest request = ((ServletRequestAttributes) attrs).getRequest();
		// 判断是不是JSON请求
		if (isJson(viewName, request)) {
			return view;
		} else {
			return null;
		}
	}

	private boolean isJson(String viewName, HttpServletRequest request) {
		// 后缀判断
		if (StringUtils.isEmpty(viewName) && viewName.toLowerCase().endsWith(getSuffix())) { return true; }
		// 请求类型判断
		String accept = request.getHeader(HttpHeaders.ACCEPT);
		if (MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(accept)) { return true; }
		if (MediaType.APPLICATION_JSON_UTF8_VALUE.equalsIgnoreCase(accept)) { return true; }
		// 后缀名判断
		String url = request.getRequestURI();
		if (!StringUtils.isEmpty(url) && url.toLowerCase().endsWith(suffix)) { return true; }

		return false;
	}

}
